<template>
  <div class="user-management">
    <el-card class="box-card" header="批量用户管理">
      <div class="search-bar">
        <el-input v-model="searchType" placeholder="搜索用户类型" class="search-input" />
        <el-input v-model="searchGrade" placeholder="搜索年级" class="search-input" />
        <el-select v-model="searchDormGroup" placeholder="搜索宿舍组团" class="search-input">
          <el-option value="一号组团" label="一号组团"></el-option>
          <el-option value="二号组团" label="二号组团"></el-option>
          <el-option value="三号组团" label="三号组团"></el-option>
          <el-option value="" label="不选"></el-option>
        </el-select>
        <el-select v-model="searchDormBuilding" placeholder="搜索宿舍楼栋" class="search-input">
          <el-option v-for="i in 30" :key="i" :value="'#' + i" :label="'#' + i"></el-option>
          <el-option value="" label="不选"></el-option>
        </el-select>
        <el-button @click="searchUsers" class="search-button" type="primary" icon="el-icon-search">搜索</el-button>
        <el-button @click="deleteSelectedUsers" class="delete-button" type="danger" icon="el-icon-delete" :disabled="selectedRows.length === 0">批量删除</el-button>
      </div>
      <div class="table-container">
        <el-table
            :data="users"
            :loading="loading"
            border
            @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="userNo" label="用户编号"></el-table-column>
          <el-table-column prop="name" label="姓名"></el-table-column>
          <el-table-column prop="gender" label="性别"></el-table-column>
          <el-table-column prop="type" label="用户类型"></el-table-column>
          <el-table-column prop="grade" label="年级"></el-table-column>
          <el-table-column prop="dormGroup" label="宿舍组团"></el-table-column>
          <el-table-column prop="dormBuilding" label="宿舍楼栋"></el-table-column>
          <el-table-column prop="dormRoom" label="宿舍号"></el-table-column>
        </el-table>
      </div>
      <div class="pagination-container">
        <el-pagination
            v-model:current-page="page"
            v-model:page-size="pageSize"
            :total="total"
            @current-change="fetchUsers"
            class="pagination"
        />
      </div>
    </el-card>

    <!-- 修改用户对话框 -->
    <el-dialog :visible.sync="userDialogVisible" :title="dialogTitle" width="500px">
      <el-form :model="userForm" :rules="rules" ref="userFormRef" @submit.native.prevent="handleUserDialogConfirm">
        <el-form-item label="用户编号" prop="userNo">
          <el-input v-model="userForm.userNo" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="userForm.name" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="userForm.gender">
            <el-option value="男" label="男"></el-option>
            <el-option value="女" label="女"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用户类型" prop="type">
          <el-input v-model="userForm.type" />
        </el-form-item>
        <el-form-item label="年级" prop="grade">
          <el-input v-model="userForm.grade" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="userForm.password" />
        </el-form-item>
        <el-form-item label="宿舍组团" prop="dormGroup">
          <el-select v-model="userForm.dormGroup">
            <el-option value="一号组团" label="一号组团"></el-option>
            <el-option value="二号组团" label="二号组团"></el-option>
            <el-option value="三号组团" label="三号组团"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="宿舍楼栋" prop="dormBuilding">
          <el-select v-model="userForm.dormBuilding">
            <el-option v-for="i in 30" :key="i" :value="'#' + i" :label="'#' + i"/>
          </el-select>
        </el-form-item>
        <el-form-item label="宿舍号" prop="dormRoom">
          <el-input v-model="userForm.dormRoom" />
        </el-form-item>
        <!-- 创建时间和更新时间 -->
        <el-form-item label="创建时间" prop="createTime">
          <el-date-picker v-model="userForm.createTime" type="datetime" format="yyyy-MM-dd HH:mm:ss" />
        </el-form-item>
        <el-form-item label="更新时间" prop="updateTime">
          <el-date-picker v-model="userForm.updateTime" type="datetime" format="yyyy-MM-dd HH:mm:ss" />
        </el-form-item>
        <div class="dialog-footer">
          <el-button @click="handleDialogCancel">取消</el-button>
          <el-button type="primary" @click="handleUserDialogConfirm">确认</el-button>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import axios from 'axios';
import { ElMessage } from 'element-plus';

const searchName = ref('');
const searchUserNo = ref('');
const searchType = ref('');
const searchGrade = ref('');
const searchDormGroup = ref('');
const searchDormBuilding = ref('');
const users = ref([]);
const loading = ref(false);
const page = ref(1);
const pageSize = ref(10);
const total = ref(0);

const selectedRows = ref([]);
const userDialogVisible = ref(false);
const dialogTitle = ref('');
const userFormRef = ref(null);
const userForm = reactive({
  userNo: '',
  name: '',
  gender: '',
  type: '',
  grade: '',
  email: '',
  password: '',
  dormGroup: '',
  dormBuilding: '',
  dormRoom: '',
  createTime: '',
  updateTime: '',
});
const rules = {
  userNo: [{ required: true, message: '用户编号不能为空', trigger: 'blur' }],
  name: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
  email: [{ required: true, type: 'email', message: '邮箱格式不正确', trigger: 'blur' }],
  password: [{ required: true, message: '密码不能为空', trigger: 'blur' }],
};

const fetchUsers = async () => {
  loading.value = true;
  try {
    const response = await axios.post('http://localhost:8080/users/listUsersPage1', {
      pageNum: page.value,
      pageSize: pageSize.value,
      param: {
        name: searchName.value,
        userNo: searchUserNo.value,
        type: searchType.value,
        grade: searchGrade.value,
        dormGroup: searchDormGroup.value,
        dormBuilding: searchDormBuilding.value
      }
    });
    users.value = response.data.data;
    total.value = response.data.total;
  } catch (error) {
    console.error('获取用户数据失败:', error);
    ElMessage.error('获取用户数据失败');
  } finally {
    loading.value = false;
  }
};

const searchUsers = () => {
  page.value = 1;
  fetchUsers();
};

const deleteSelectedUsers = async () => {
  const confirm = window.confirm('确定批量删除这些用户吗？');
  if (confirm) {
    try {
      const idsToDelete = selectedRows.value.map(item => item.userId);
      const userDto = { userIdList: idsToDelete };
      await axios.post('http://localhost:8080/users/deleteBatch', userDto);
      fetchUsers();
      selectedRows.value = []; // 清空已选数据
      ElMessage.success('批量删除成功');
    } catch (error) {
      console.error('批量删除用户失败:', error);
      ElMessage.error('批量删除用户失败');
    }
  }
};

const handleSelectionChange = (selected) => {
  selectedRows.value = selected;
};

const openEditUserDialog = (user) => {
  dialogTitle.value = '编辑用户';
  Object.assign(userForm, user);
  userDialogVisible.value = true;
};

const handleDialogCancel = () => {
  userDialogVisible.value = false;
};

const handleUserDialogConfirm = async () => {
  try {
    const formRef = userFormRef.value;
    if (formRef) {
      await formRef.validate();
      await axios.post('http://localhost:8080/users/saveOrUpdate', userForm);
      ElMessage.success('操作成功');
      userDialogVisible.value = false;
      fetchUsers();
    }
  } catch (error) {
    console.error('保存用户数据失败:', error);
    ElMessage.error('保存用户数据失败');
  }
};

onMounted(() => {
  fetchUsers();
});
</script>

<style scoped>
.box-card /deep/ .el-card__header {
  font-size: 20px;
  font-weight: bold;
}
.user-management {
  padding: 20px;
}
.search-bar {
  margin-bottom: 20px;
}
.search-input {
  width: 200px;
  margin-right: 10px;
}
.search-button {
  margin-right: 10px;
}
.delete-button {
  margin-left: 10px;
}
.table-container {
  margin-bottom: 20px;
}
.pagination-container {
  text-align: center;
}
.dialog-footer {
  text-align: right;
}
</style>
